package cn.zhentao.controller;


import cn.zhentao.pojo.TCarInfo;
import cn.zhentao.service.TCarInfoService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("carInfo")
@CrossOrigin(origins = "*") // 允许跨域访问
public class CarInfoController {


    @Autowired
    private TCarInfoService tCarInfoService;

    /**查询所有 附带分页 条件*/
    @PostMapping("findList")
    public Map<String, Object> findList(@RequestBody Map<String, Object> params){
        try {
            // 获取分页参数
            Integer page = (Integer) params.getOrDefault("page", 1);
            Integer pageSize = (Integer) params.getOrDefault("pageSize", 10);
            String brandId = (String) params.get("brandId");
            String sortType = (String) params.getOrDefault("sortType", "default");

            // 创建分页对象
            Page<TCarInfo> pageObj = new Page<>(page, pageSize);
            
            // 创建查询条件
            QueryWrapper<TCarInfo> queryWrapper = new QueryWrapper<>();
            
            // 只查询已上架的车辆
            queryWrapper.eq("status", 1);
            
            // 品牌筛选
            if (brandId != null && !"all".equals(brandId) && !brandId.trim().isEmpty()) {
                queryWrapper.eq("brand_id", brandId);
            }
            
            // 排序
            switch (sortType) {
                case "price":
                    queryWrapper.orderByAsc("price");
                    break;
                case "mileage":
                    queryWrapper.orderByAsc("mileage");
                    break;
                case "location":
                    queryWrapper.orderByDesc("create_time"); // 按发布时间排序
                    break;
                default:
                    queryWrapper.orderByDesc("create_time");
                    break;
            }

            // 执行分页查询
            Page<TCarInfo> result = tCarInfoService.page(pageObj, queryWrapper);
            
            // 返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", result.getRecords());
            response.put("total", result.getTotal());
            response.put("pages", result.getPages());
            response.put("current", result.getCurrent());
            response.put("size", result.getSize());
            
            return response;
            
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "查询失败: " + e.getMessage());
            errorResponse.put("data", null);
            return errorResponse;
        }
    }





    /**
     * 添加
     * @param carInfo 信息
     * @return 添加结果
     */

    @PostMapping("add")
    public String add(@RequestBody TCarInfo carInfo) {
        boolean save = tCarInfoService.save(carInfo);
        return save ? "添加成功" : "添加失败";
    }



    /**
     * 修改
     * @param carInfo 信息
     * @return 修改结果
     */
    @PostMapping("update")
    public String update(@RequestBody TCarInfo carInfo) {
        boolean update = tCarInfoService.updateById(carInfo);
        return update ? "修改成功" : "修改失败";
    }


    /**
     * 根据ID查询
     * @param id ID
     * @return 信息
     */
    @GetMapping("findById")
    public TCarInfo findById(@RequestParam Integer id) {
        return tCarInfoService.getById(id);
    }

    /**
     * 根据ID查询车辆详情（小程序专用）
     * @param id 车辆ID
     * @return 详细信息
     */
    @GetMapping("findDetailById")
    public Map<String, Object> findDetailById(@RequestParam Integer id) {
        try {
            TCarInfo carInfo = tCarInfoService.getById(id);
            if (carInfo == null) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 404);
                errorResponse.put("message", "车辆信息不存在");
                errorResponse.put("data", null);
                return errorResponse;
            }

            // 构造详细信息响应
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            
            // 构造详细数据
            Map<String, Object> detailData = new HashMap<>();
            detailData.put("id", carInfo.getId());
            detailData.put("carCode", carInfo.getCarCode());
            detailData.put("modelName", carInfo.getModelName());
            detailData.put("brandId", carInfo.getBrandId());
            detailData.put("seriesId", carInfo.getSeriesId());
            detailData.put("price", carInfo.getPrice());
            detailData.put("mileage", carInfo.getMileage());
            detailData.put("registerTime", carInfo.getRegisterTime());
            detailData.put("displacement", carInfo.getDisplacement());
            detailData.put("fuelType", carInfo.getFuelType());
            detailData.put("gearboxType", carInfo.getGearboxType());
            detailData.put("color", carInfo.getColor());
            detailData.put("carCondition", carInfo.getCarCondition());
            detailData.put("mainPic", carInfo.getMainPic());
            detailData.put("detailDesc", carInfo.getDetailDesc());
            detailData.put("status", carInfo.getStatus());
            detailData.put("createTime", carInfo.getCreateTime());
            
            response.put("data", detailData);
            return response;
            
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "查询失败: " + e.getMessage());
            errorResponse.put("data", null);
            return errorResponse;
        }
    }

    /**
     * 删除
     * @param id ID
     * @return 删除结果
     */
    @GetMapping("delete")
    public String delete(@RequestParam Integer id) {
        boolean delete = tCarInfoService.removeById(id);
        return delete ? "删除成功" : "删除失败";
    }
}

